package com.yisu.auction.api.web.controller;

import com.google.common.collect.Lists;
import com.yisu.auction.api.core.service.*;
import com.yisu.auction.api.domain.request.prizePackage.PrizeDetailRequest;
import com.yisu.auction.api.domain.request.rechargePackage.RechargeRequest;
import com.yisu.auction.api.domain.request.tradePackage.PaymentRequest;
import com.yisu.auction.api.domain.request.tradePackage.TradeRequest;
import com.yisu.auction.api.domain.response.tradePackage.PaymentDetailResponse;
import com.yisu.auction.api.domain.vo.PrizePackageVos.ReceivingAddressVo;
import com.yisu.auction.api.domain.vo.goodsInfoPackageVos.PrizeButtonVo;
import com.yisu.auction.api.domain.vo.tradePackageVos.PaymentDetailVo;
import com.yisu.auction.api.domain.vo.tradePackageVos.RechargeCardVo;
import com.yisu.auction.api.domain.vo.tradePackageVos.TimerShaftVo;
import com.yisu.auction.api.web.interceptor.IAuthVerifyAnnotation;
import com.yisu.auction.api.web.utils.PingppUtil;
import com.yisu.auction.ewf.common.enums.LoginTypeEnum;
import com.yisu.auction.ewf.common.enums.ResponseCode;
import com.yisu.auction.ewf.common.web.JsonResult;
import com.yisu.auction.ewf.entity.Prize;
import com.yisu.auction.ewf.entity.RechargeableCard;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * author: 赵杰
 * Business Description：交易业务
 * createTime：2017/8/18
 */
@Controller
@RequestMapping(value = "/trade")
public class TradeController extends BaseController {
    @Resource
    private ITradeService iTradeService;
    @Resource
    private IPrizeService iPrizeService;
    @Resource
    private IOfferPriceLogService iOfferPriceLogService;
    @Resource
    private IRechargeService iRechargeService;
    @Resource
    private IAddressService iAddressService;
    @Resource
    private IRechargeableCardService iRechargeableCardService;


    /**
     * author: 赵杰
     * Business Description：竞拍出价接口
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/offerPriceForJob", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult offerPriceForJob(TradeRequest tradeRequest) {
        return iTradeService.offerPriceForJob(tradeRequest);
    }


    /**
     * author: 赵杰
     * Business Description：竞拍出价接口
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/offerPrice", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult offerPrice(TradeRequest tradeRequest) {
        try {
            if (StringUtils.isEmpty(tradeRequest.getMemberId())) {
                this.userToken = tradeRequest.getUserToken();
                tradeRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
            }
            return iTradeService.offerPrice(tradeRequest);
        } catch (Exception e) {
            logger.error("竞拍出价接口异常：" + e.getMessage());
        }
        return new JsonResult(-1, "网络君泡妞了");
    }

    /**
     * author: 赵杰
     * Business Description：开出竞拍结果
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/openPrizeResult", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NO_NEED_LOGIN)
    public JsonResult openPrizeResult(TradeRequest tradeRequest) {
        return iTradeService.openPrizeResult(tradeRequest);
    }


    /**
     * author: 赵杰
     * Business Description：差价购买
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/paymentDetail", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult paymentDetail(PaymentRequest paymentRequest) throws InterruptedException, UnsupportedEncodingException {
        /**
         * 逻辑：优先判断此用户是否拍中，未拍中则不能进行差价购
         *       其次，看商品总额与出价差值进行支付
         */
        PaymentDetailResponse paymentDetailResponse = new PaymentDetailResponse();
        PaymentDetailVo paymentDetailVo = new PaymentDetailVo();
        List<TimerShaftVo> timerShaftVos = Lists.newArrayList();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.userToken = paymentRequest.getUserToken();
        paymentRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        Prize prize = iPrizeService.getPrizeModelByPrizeId(paymentRequest.getPrizeId());
        if (prize == null) {
            return new JsonResult(-1, "非法请求");
        }
        if (!(prize.getMemberId() + "").equals(paymentRequest.getMemberId())) {
            return new JsonResult(-1, "无购买资格");
        }
        paymentDetailVo.setName(prize.getName());
        paymentDetailVo.setAnnounceTime(prize.getAnnounceTime());
        if (!StringUtils.isEmpty(prize.getImage())) {
            paymentDetailVo.setImage(Linq4j.asEnumerable(prize.getImage().split(",")).toList().get(0));
        }
        paymentDetailVo.setIsRechargeCard(prize.getIsRechargeableCard());
        paymentDetailVo.setTransactionPrice(prize.getTransactionPrice());
        paymentDetailResponse.setPaymentDetailVo(paymentDetailVo);
        boolean isRechargeCard = prize.getIsRechargeableCard() == 1;// 是否是充值卡类
        List<RechargeCardVo> rechargeCardVos = Lists.newArrayList();
        if (isRechargeCard) {
            List<RechargeableCard> rechargeableCards = iRechargeableCardService.getRechargeableCardListByPrizeId(prize.getId());
            if (!CollectionUtils.isEmpty(rechargeableCards)) {
                for (RechargeableCard rechargeableCard : rechargeableCards) {
                    RechargeCardVo rechargeCardVo = new RechargeCardVo();
                    rechargeCardVo.setCardNumber(rechargeableCard.getCardNo());
                    rechargeCardVo.setCardPassword(rechargeableCard.getCardPwd());
                    switch (rechargeableCard.getBillType()) {
                        case 1:
                            rechargeCardVo.setCardValue("移动" + rechargeableCard.getCardValue() + "充值卡");
                            rechargeCardVo.setExchangeExplainUrl("http://qiniu.ddbaoxiang.com/170920172654447311303956.jpg");
                            break;
                        case 2:
                            rechargeCardVo.setCardValue("联通" + rechargeableCard.getCardValue() + "充值卡");
                            rechargeCardVo.setExchangeExplainUrl("http://qiniu.ddbaoxiang.com/170920172630445382535632.jpg");
                            break;
                        case 3:
                            rechargeCardVo.setCardValue("电信" + rechargeableCard.getCardValue() + "充值卡");
                            rechargeCardVo.setExchangeExplainUrl("http://qiniu.ddbaoxiang.com/170920172559455805926211.jpg");
                            break;
                        case 4:
                            rechargeCardVo.setCardValue("京东" + rechargeableCard.getCardValue() + "E卡");
                            rechargeCardVo.setExchangeExplainUrl("http://qiniu.ddbaoxiang.com/170920172848133164774250.jpg");
                            break;
                    }
                    rechargeCardVos.add(rechargeCardVo);
                }
            }

        }
        //绑定时间轴
        if (prize.getOrderStatus() == 0) {//未付款
            timerShaftVos.add(new TimerShaftVo("未付款", "",
                    Lists.<PrizeButtonVo>newArrayList(new PrizeButtonVo("去付款", "treasurebox://ddbaoxiang.com/buyPrize/" + prize.getId() + "/" + prize.getTransactionPrice())),
                    Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 1, 1));
            timerShaftVos.add(new TimerShaftVo("等待发货", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 2, 0));
            timerShaftVos.add(new TimerShaftVo("等待收货", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 3, 0));
            timerShaftVos.add(new TimerShaftVo("等待晒单", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 4, 0));
            timerShaftVos.add(new TimerShaftVo("完成", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 5, 0));
        }
        if (prize.getOrderStatus() == 1) {//已付款
            timerShaftVos.add(new TimerShaftVo("已付款", simpleDateFormat.format(prize.getPaymentTime()), Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 1, 0));
            if (!isRechargeCard) {//非充值卡类，判断是否添加充值卡
                if (StringUtils.isEmpty(prize.getAddress())) {
                    timerShaftVos.add(new TimerShaftVo("请填写收货地址", "",
                            Lists.newArrayList(new PrizeButtonVo("选择地址", "treasurebox://ddbaoxiang.com/addressList/1")),
                            Lists.<String>newArrayList(),
                          /*  Lists.newArrayList("收货人：" + receivingAddressVo.getLinker(), "手机号码：" + receivingAddressVo.getMobile(),
                                    "详细地址：" + receivingAddressVo.getProvince() + receivingAddressVo.getCity() + receivingAddressVo.getRegion() + receivingAddressVo.getRegion() + receivingAddressVo.getCountry()+receivingAddressVo.getDetail()),*/
                            Lists.<RechargeCardVo>newArrayList(), 2, 1));
                } else {
                    timerShaftVos.add(new TimerShaftVo("收货地址", "",
                            Lists.newArrayList(new PrizeButtonVo("选择地址", "treasurebox://ddbaoxiang.com/addressList/1")),
                            isRechargeCard == true ? Lists.<String>newArrayList() : Lists.newArrayList("收货人：" + prize.getRecer(), "手机号码：" + prize.getLinkPhone(),
                                    "详细地址：" + prize.getAddress()),
                            Lists.<RechargeCardVo>newArrayList(), 2, 1));
                    timerShaftVos.add(new TimerShaftVo("等待发货", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 3, 0));
                }
            } else {
                timerShaftVos.add(new TimerShaftVo("等待发货", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 3, 0));
            }
            timerShaftVos.add(new TimerShaftVo("等待收货", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 4, 0));
            timerShaftVos.add(new TimerShaftVo("等待晒单", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 5, 0));
            timerShaftVos.add(new TimerShaftVo("完成", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 6, 0));
        }
        if (prize.getOrderStatus() == 2) {
            timerShaftVos.add(new TimerShaftVo("已付款", simpleDateFormat.format(prize.getPaymentTime()), Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 1, 0));
            timerShaftVos.add(new TimerShaftVo("已发货", simpleDateFormat.format(prize.getSendTime()), Lists.<PrizeButtonVo>newArrayList(),
                    isRechargeCard == true ? Lists.<String>newArrayList() : Lists.newArrayList("收货人：" + prize.getRecer(), "手机号码：" + prize.getLinkPhone(),
                            "详细地址：" + prize.getAddress()), Lists.<RechargeCardVo>newArrayList(), 2, 0));
            timerShaftVos.add(new TimerShaftVo("等待收货", "",
                    Lists.newArrayList(new PrizeButtonVo("确认收货", "treasurebox://ddbaoxiang.com/confirmReceipt/" + prize.getId())),
                    isRechargeCard == true ? Lists.<String>newArrayList() : Lists.<String>newArrayList("物流公司：" + prize.getExpressCompany(), "物流单号：" + prize.getExpressNo()),
                    Lists.<RechargeCardVo>newArrayList(), 3, 1));
            timerShaftVos.add(new TimerShaftVo("等待晒单", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 4, 0));
            timerShaftVos.add(new TimerShaftVo("完成", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 5, 0));
        }
        if (prize.getOrderStatus() == 3) {
            timerShaftVos.add(new TimerShaftVo("已付款", simpleDateFormat.format(prize.getPaymentTime()), Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 1, 0));
            timerShaftVos.add(new TimerShaftVo("已发货", simpleDateFormat.format(prize.getSendTime()), Lists.<PrizeButtonVo>newArrayList(),
                    isRechargeCard == true ? Lists.<String>newArrayList() : Lists.newArrayList("收货人：" + prize.getRecer(), "手机号码：" + prize.getLinkPhone(),
                            "详细地址：" + prize.getAddress()),
                    Lists.<RechargeCardVo>newArrayList(), 3, 0));
            timerShaftVos.add(new TimerShaftVo("已收货", simpleDateFormat.format(prize.getConfirmTime()),
                    Lists.<PrizeButtonVo>newArrayList(),
                    isRechargeCard == true ? Lists.<String>newArrayList() : Lists.<String>newArrayList("物流公司：" + prize.getExpressCompany(), "物流单号：" + prize.getExpressNo()),
                    isRechargeCard == true ? rechargeCardVos : Lists.<RechargeCardVo>newArrayList(),
                    3, 0));
            timerShaftVos.add(new TimerShaftVo(prize.getShowOrderTime() != null ? "已晒单" : "等待晒单", "",
                    prize.getShowOrderTime() != null ? Lists.<PrizeButtonVo>newArrayList() : Lists.newArrayList(new PrizeButtonVo("去晒单", "treasurebox://ddbaoxiang.com/shareMyPrize/" + prize.getId() + "/" + prize.getName())),
                    Lists.<String>newArrayList(),
                    Lists.<RechargeCardVo>newArrayList(),
                    4, prize.getShowOrderTime() != null ? 0 : 1));
            timerShaftVos.add(new TimerShaftVo("完成", "", Lists.<PrizeButtonVo>newArrayList(), Lists.<String>newArrayList(), Lists.<RechargeCardVo>newArrayList(), 5, prize.getShowOrderTime() != null ? 1 : 0));
        }
        paymentDetailResponse.setTimerShaftVos(timerShaftVos);
        return new JsonResult(paymentDetailResponse);

    }


    /**
     * author: 赵杰
     * Business Description：去付款
     *
     * @param
     * @return 系统参数
     */
    @RequestMapping(value = "/priceSpreadBuy", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    @ResponseBody
    @IAuthVerifyAnnotation(Desc = "登录验证", LoginTypeEnum = LoginTypeEnum.NEED_LOGIN)
    public JsonResult priceSpreadBuy(PaymentRequest paymentRequest) throws InterruptedException, UnsupportedEncodingException {
        /**
         * 逻辑：优先判断此用户是否拍中，未拍中则不能进行差价购
         *       其次，看商品总额与出价差值进行支付
         */
        this.userToken = paymentRequest.getUserToken();
        paymentRequest.setMemberId(String.valueOf(this.getToken().getMemberId()));
        Prize prize = iPrizeService.getPrizeModelByPrizeId(paymentRequest.getPrizeId());
        if (prize == null) {
            return new JsonResult(-1, "非法请求");
        }
        if (!(prize.getMemberId() + "").equals(paymentRequest.getMemberId())) {
            return new JsonResult(-1, "无购买资格");
        }
        //查看用户此次购买总额
        PrizeDetailRequest prizeDetailRequest = new PrizeDetailRequest();
        prizeDetailRequest.setMemberId(paymentRequest.getMemberId());
        prizeDetailRequest.setPrizeId(paymentRequest.getPrizeId());
        //剩余支付金额
        BigDecimal payableAmount = prize.getTransactionPrice();
        RechargeRequest rechargeRequest = new RechargeRequest();
        rechargeRequest.setPayType(paymentRequest.getPayType());
        rechargeRequest.setAmount(String.valueOf(payableAmount));
        rechargeRequest.setDescription(paymentRequest.getPrizeId() + "");
        rechargeRequest.setOrderSign("PRICESPREADBUY");
        rechargeRequest.setMemberId(paymentRequest.getMemberId());
        rechargeRequest.setAppType(paymentRequest.getAppType());
        String orderNo = iRechargeService.createRechargeOrder(rechargeRequest);
        String chargeStr = PingppUtil.getChargeCommon(orderNo, prize.getTransactionPrice() + "", paymentRequest.getPayType(), "", paymentRequest.getAppSign());
        if (!StringUtils.isEmpty(chargeStr)) {
            JsonResult result = new JsonResult();
            result.setData(chargeStr);
            return result;
        }
        return new JsonResult(ResponseCode.FAILURE.code, ResponseCode.FAILURE.msg);

    }
}
